package com.cavasmonitor;

import java.util.ArrayList;
import java.util.List;

import com.cavasmonitor.db.CavasDao;
import com.cavasmonitor.to.EquipoTo;
import com.cavasmonitor.to.UsuarioTo;
import com.cavasmonitor.to.UsuarioTo.Rol;
import com.cavasmonitor.util.Session;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

public class UsuariosActivity extends Activity {

	Spinner s;
	Long id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.usuarios);

		id = 0L;

		s = (Spinner) findViewById(R.id.spiPrivilegios);
		ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
				R.array.privilegios, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(adapter);

		CavasDao dao = new CavasDao(UsuariosActivity.this);
		dao.open();

		List<UsuarioTo> usuarios = dao.getUsuarios();
		List<String> list = new ArrayList<String>();

		list.add("Seleccione el usuario a editar");
		if (usuarios != null && !usuarios.isEmpty())
			for (UsuarioTo u : usuarios) {
				list.add(u.getNombre());
			}
		s = (Spinner) findViewById(R.id.spiUsuarios);
		ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, list);
		spinnerArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(spinnerArrayAdapter);

		dao.close();

		Button btn = (Button) findViewById(R.id.btnGuardar);

		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				String user = ((EditText) findViewById(R.id.inputUser))
						.getText().toString().trim();
				String pass = ((EditText) findViewById(R.id.inputPass))
						.getText().toString().trim();
				Long spi = ((Spinner) findViewById(R.id.spiPrivilegios))
						.getSelectedItemId();

				if (user.length() == 0) {
					new AlertDialog.Builder(UsuariosActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_usuario_rq_c)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (user.length() < 4) {
					new AlertDialog.Builder(UsuariosActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_usuario_len)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (pass.length() == 0) {
					new AlertDialog.Builder(UsuariosActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_pass_rq_c)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (pass.length() < 4) {
					new AlertDialog.Builder(UsuariosActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_pass_len)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (spi == 0) {
					new AlertDialog.Builder(UsuariosActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_privi_rq)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else {

					CavasDao dao = new CavasDao(UsuariosActivity.this);
					dao.open();

					UsuarioTo usuario = dao.getUsuario(user);

					UsuarioTo update = new UsuarioTo();
					if (id > 0) {
						update = dao.getUsuario(id);
					}

					if (usuario != null && id == 0) {
						new AlertDialog.Builder(UsuariosActivity.this)
								.setTitle(R.string.msg_atencion)
								.setMessage(R.string.msg_usuario_existe)
								.setNeutralButton(R.string.msg_aceptar, null)
								.show();
					} else if (id > 0
							&& usuario != null
							&& !usuario.getNombre().equalsIgnoreCase(
									update.getNombre())) {
						new AlertDialog.Builder(UsuariosActivity.this)
								.setTitle(R.string.msg_atencion)
								.setMessage(R.string.msg_usuario_rep)
								.setNeutralButton(R.string.msg_aceptar, null)
								.show();
					} else {

						usuario = new UsuarioTo();
						usuario.setId(id);
						usuario.setNombre(user);
						usuario.setPass(pass);
						usuario.setRol(UsuarioTo.Rol.getRol(spi));

						if (id == 0) {
							dao.createUsuario(usuario);
						} else {
							dao.updateUsuario(usuario);
						}

						dao.close();
						new AlertDialog.Builder(UsuariosActivity.this)
								.setTitle(R.string.msg_atencion)
								.setMessage(R.string.msg_usuario_success)
								.setNeutralButton(R.string.msg_aceptar, null)
								.show();

						Intent i = new Intent(UsuariosActivity.this,
								UsuariosActivity.class);
						startActivityForResult(i, 1);
					}

					dao.close();
				}

			}
		});

		ImageButton img = (ImageButton) findViewById(R.id.btnHome);

		img.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent i = new Intent(UsuariosActivity.this,
						OpcionesActivity.class);
				startActivityForResult(i, 1);
			}
		});

		img = (ImageButton) findViewById(R.id.btnExit);

		img.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				new AlertDialog.Builder(UsuariosActivity.this)
						.setTitle(R.string.msg_salir)
						.setMessage(R.string.msg_logout)
						.setPositiveButton(R.string.msg_aceptar,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										Session.usuario = null;
										Intent i = new Intent(
												UsuariosActivity.this,
												MainActivity.class);
										startActivityForResult(i, 1);
									}
								})
						.setNegativeButton(R.string.msg_cancelar, null).show();

			}
		});

		s.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView,
					View selectedItemView, int position, long idx) {

				if (position > 0) {

					CavasDao dao = new CavasDao(UsuariosActivity.this);
					dao.open();

					String nombreUsuario = s.getSelectedItem().toString()
							.trim();

					UsuarioTo usuario = dao.getUsuario(nombreUsuario);

					id = usuario.getId();

					EditText edt = (EditText) findViewById(R.id.inputUser);
					edt.setText(usuario.getNombre());

					edt = (EditText) findViewById(R.id.inputPass);
					edt.setText(usuario.getPass());

					Spinner rol = (Spinner) findViewById(R.id.spiPrivilegios);
					rol.setSelection(usuario.getRol().getId().intValue());

				} else {
					id = 0L;

					EditText edt = (EditText) findViewById(R.id.inputUser);
					edt.setText("");

					edt = (EditText) findViewById(R.id.inputPass);
					edt.setText("");

					Spinner rol = (Spinner) findViewById(R.id.spiPrivilegios);
					rol.setSelection(0);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {
				// your code here
			}
		});
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i;
		switch (item.getOrder()) {
		case Session.M_USUARIOS:
			i = new Intent(UsuariosActivity.this, UsuariosActivity.class);
			startActivityForResult(i, 1);
			return true;
		case Session.M_CFG:
			i = new Intent(UsuariosActivity.this, ConfiguracionActivity.class);
			startActivityForResult(i, 1);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		if (Session.usuario.getRol() == UsuarioTo.Rol.ADMINISTRADOR) {
			getMenuInflater().inflate(R.menu.main, menu);
		} 
		return true;
	}
}
